package com.yanxu.stopthreads;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/7/21-2024
 * @Description: 没有阻塞的情况下，正确停止线程的方法
 */
public class RightWayStopThreadWithSleepEventLoop {

    public static void main(String[] args) throws InterruptedException {
        //mainSolve1(args);
        mainSolve2(args);
    }


    public static void mainWrong(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                int num = 0;
                while (num <= 100000) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数");
                    }
                    System.out.println(num);
                    num++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("任务运行结束了");
            }
        });

        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }

    public static void mainSolve1(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                int num = 0;
                try {
                    while (num <= 300) {
                        if (num % 100 == 0) {
                            System.out.println(num + "是100的倍数");
                        }
                        System.out.println(num);
                        num++;
                        Thread.sleep(20);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println("任务运行结束了");
            }
        });

        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }

    public static void mainSolve2(String[] args) throws InterruptedException {
        final Thread thread = new Thread(new Runnable() {
            public void run() {
                int num = 0;
                while (num <= 300 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数");
                    }
                    System.out.println(num);
                    num++;
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();  //重新设置 中断信号。
                        e.printStackTrace();
                    }
                }
                System.out.println("任务运行结束了");
            }
        });

        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}